package com.junqson.je.msg.service;

import com.alibaba.fastjson.JSONObject;
import com.junqson.je.msg.model.MessageModel;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Descriptions websocket 消息 redis监听回调
 * @Company
 * @Author Junqson
 * @Date 2020/2/10 15:31
 * @Version 1.0
 */
@Service
@Slf4j
public class MessageService {

    public static String MESSAGE_CHANNEL = "message";

    public static String CLOSE_CHANNEL = "close";

    public static String OUT_MSG = "out_msg";


    @Resource
    private WebSocketService webSocketService;

    @Resource
    private MsgCrudService msgCrudService;

    public void receiveMessage(String message, String channel) {
        log.info("receive message channel {}, message {}", channel, message);
        if (MESSAGE_CHANNEL.equals(channel)) {
            WsMessage wsMessage = JSONObject.parseObject(message, WsMessage.class);
            webSocketService.sendMessage(wsMessage.getUserId(), wsMessage.getMessage());
        } else if (CLOSE_CHANNEL.equals(channel)) {
            webSocketService.close(Integer.valueOf(message));
        } else if (OUT_MSG.equals(channel)) {
            try {
                MessageModel msg = JSONObject.parseObject(message, MessageModel.class);
                msgCrudService.save(msg);
            } catch (Exception e) {
                log.error("【消息投递失败】msg = {}", message);
            }
        }
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class WsMessage {
        private Integer userId;

        private String message;
    }

}
